package com.adms.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.adms.domain.ReformView;
import com.adms.domain.ReformViewExample;
import com.adms.domain.ReformViewExample.Criteria;
import com.adms.domain.ReformViewMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;

@Transactional
@Service
public class ReformViewService {

	@Autowired
	private ReformViewMapper reformViewMapper;

	public ReformView getByViewId(Integer viewId) {
		return reformViewMapper.selectByPrimaryKey(viewId);
	}

	public Map<String,Object> getByViewIdWithReform(Integer viewId) {
		return reformViewMapper.selectByPrimaryKeyWithReform(viewId);
	}

	public PageInfo<ReformView> list(ReformView reformView, String timeField, Date start, Date end,
			String orderByClause, Integer pageNum, Integer pageSize, Integer navigatePages) {
		
		ReformViewExample ex = constructExample(reformView,timeField, start, end, orderByClause);
		PageHelper.startPage(pageNum, pageSize);
		List<ReformView> reformViews = reformViewMapper.selectByExample(ex);
		return new PageInfo<>(reformViews, navigatePages);
	}
	
	private ReformViewExample constructExample(ReformView reformView, String timeField, Date start, Date end,
			String orderByClause) {
		ReformViewExample ex = new ReformViewExample();
		Criteria or = ex.or();
		if(reformView != null) {
			Integer reformId = reformView.getReformId();
			if(reformId != null) {
				or.andReformIdEqualTo(reformId);
			}
		}
		
		if(StringUtil.isNotEmpty(timeField)) {
			if(timeField.equals("createTime")) {
				if(start != null) {
					if(end != null) {
						or.andCreateTimeBetween(start, end);
					}else {
						or.andCreateTimeGreaterThanOrEqualTo(start);
					}
				}else {
					if(end != null) {
						or.andCreateTimeLessThanOrEqualTo(end);
					}
				}
			}
		}
	
		if(StringUtil.isNotEmpty(orderByClause)) {
			ex.setOrderByClause(orderByClause);
		}else {
			ex.setOrderByClause("reform_view.create_time desc");
		}
		return ex;
	}
}